package com.ruoyi.taskSys.service.impl;

import java.io.*;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import com.ruoyi.baseSys.mapper.MHouseholdInfoMapper;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.taskSys.domain.MHouseholdTask;
import com.ruoyi.taskSys.mapper.MHouseholdTaskMapper;
import com.ruoyi.taskSys.pojo.TaskRo;
import com.ruoyi.util.AESUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.taskSys.mapper.MBuildingTaskMapper;
import com.ruoyi.taskSys.domain.MBuildingTask;
import com.ruoyi.taskSys.service.IMBuildingTaskService;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;


/**
 * 楼栋核酸任务Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-07-28
 */
@Service
public class MBuildingTaskServiceImpl implements IMBuildingTaskService
{
    @Autowired
    private MBuildingTaskMapper mBuildingTaskMapper;

    @Autowired
    private MHouseholdInfoMapper mHouseholdInfoMapper;

    @Autowired
    private MHouseholdTaskMapper mHouseholdTaskMapper;

    private String secretId= "AKIDhLWedUDsPuLgsHqKzeQDNZ0QTWSDHVsP";
    private String secretKey="JlFpBhYPuS8nM1dJylaM8oIqSC6ts1Nl";
    private String bucketName= "fccar-zz-1327923516";
    private String resultUrl = "https://%s.cos.%s.myqcloud.com/%s";


    private static final String url = "http://localhost/hslog?";

    private static final int QR_CODE_SIZE = 200;



    /**
     * 查询楼栋核酸任务
     * 
     * @param id 楼栋核酸任务主键
     * @return 楼栋核酸任务
     */
    @Override
    public MBuildingTask selectMBuildingTaskById(Long id)
    {
        return mBuildingTaskMapper.selectMBuildingTaskById(id);
    }

    /**
     * 查询楼栋核酸任务列表
     * 
     * @param mBuildingTask 楼栋核酸任务
     * @return 楼栋核酸任务
     */
    @Override
    public List<MBuildingTask> selectMBuildingTaskList(MBuildingTask mBuildingTask)
    {
        return mBuildingTaskMapper.selectMBuildingTaskList(mBuildingTask);
    }

    /**
     * 新增楼栋核酸任务
     * 
     * @param mBuildingTask 楼栋核酸任务
     * @return 结果
     */
    @Override
    public int insertMBuildingTask(MBuildingTask mBuildingTask)
    {   //创建任务名
        //截取时间
        Date date=mBuildingTask.getStartTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = sdf.format(date);
        String year = dateString.substring(0, 4);
        String month = dateString.substring(5, 7);
        String day = dateString.substring(8);
        dateString=year+"年"+month+"月"+day+"日";
        //获取楼栋名
        Long bdid=mBuildingTask.getBuildding();
        String bdname= mBuildingTaskMapper.getbdid(bdid);
        //拼接任务名
        String taskName = dateString+" "+bdname+"检测";
        mBuildingTask.setTask(taskName);

        //统计任务人数
        Long num = mBuildingTaskMapper.getnum(bdid);
        mBuildingTask.setTaskNum(num);

        //初始化状态
        mBuildingTask.setTaskStatus(0L);

        //创建住户核酸任务
        CreateHousehold(mBuildingTask);

        return mBuildingTaskMapper.insertMBuildingTask(mBuildingTask);
    }

    private void CreateHousehold(MBuildingTask mBuildingTask) {
        MHouseholdTask mHouseholdTask= new MHouseholdTask();
        Long bdid=mBuildingTask.getBuildding();
        List<String> mHouseholdInfoList = mHouseholdInfoMapper.selectHousehold(bdid);
        //创建住户核酸任务
        for (String s : mHouseholdInfoList) {
            mHouseholdTask.setTaskName(mBuildingTask.getTask());
            mHouseholdTask.setTaskStatus(mBuildingTask.getTaskStatus());
            mHouseholdTask.setHouseholdName(s);
            mHouseholdTask.setEndTime(mBuildingTask.getEndTime());
            mHouseholdTask.setStartTime(mBuildingTask.getStartTime());
            mHouseholdTask.setDetectingLocation(mBuildingTask.getDetectingLocation());

            mHouseholdTaskMapper.insertMHouseholdTask(mHouseholdTask);
        }
    }

    /**
     * 修改楼栋核酸任务
     * 
     * @param mBuildingTask 楼栋核酸任务
     * @return 结果
     */
    @Override
    public int updateMBuildingTask(MBuildingTask mBuildingTask)
    {
        return mBuildingTaskMapper.updateMBuildingTask(mBuildingTask);
    }

    /**
     * 批量删除楼栋核酸任务
     * 
     * @param ids 需要删除的楼栋核酸任务主键
     * @return 结果
     */
    @Override
    public int deleteMBuildingTaskByIds(Long[] ids)
    {
        return mBuildingTaskMapper.deleteMBuildingTaskByIds(ids);
    }

    /**
     * 删除楼栋核酸任务信息
     * 
     * @param id 楼栋核酸任务主键
     * @return 结果
     */
    @Override
    public int deleteMBuildingTaskById(Long id)
    {
        return mBuildingTaskMapper.deleteMBuildingTaskById(id);
    }

    @Override
    public String getQrcode(){
        //获取当前用户名
        String username = SecurityUtils.getUsername();
        String taskname=mHouseholdTaskMapper.selectByName(username);

        //加密的秘钥和用户名及任务名
        String key;
        String newName;
        String newTaskname;

        //AES加密
        AESUtil aesUtil = new AESUtil();
        try {
            key = aesUtil.generateAESKey();
            newName = aesUtil.encryptAES(username, key);
            newTaskname = aesUtil.encryptAES(taskname, key);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println(newName);
        System.out.println(newTaskname);

        //拼接地址
        String format = url+"user="+newName+"&task="+newTaskname;
        String imgurl;
        try {
            imgurl =getQrimg(format);
        } catch (WriterException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return imgurl;
    }

    @Override
    public String finishQrcode(TaskRo taskRo)  {
        mHouseholdTaskMapper.updateTask(taskRo);
        return "success";
    }

    public String getQrimg(String imgurl) throws WriterException, IOException {
        String text = imgurl;
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, QR_CODE_SIZE, QR_CODE_SIZE);
        Path path = FileSystems.getDefault().getPath("G:\\yuanmafile\\myruoyi\\ruoyi-admin\\qrcode.png");
        System.out.println(path);
        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
        File file=new File(path.toUri());
        return uploadImage(file);
    }

    public String uploadImage(File file) {

        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);

        Region region = new Region("ap-chongqing");
        ClientConfig clientConfig = new ClientConfig(region);
        clientConfig.setHttpProtocol(HttpProtocol.https);
        COSClient cosClient = new COSClient(cred, clientConfig);


        String key = "driver/test2.png";
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file);
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        return String.format(resultUrl, bucketName, region.getRegionName(), key);
    }
}
